package com.eet.juc.demo;

import java.util.concurrent.*;

/**
 * 传统的生产者消费者问题
 *
 * @author zheng.zhang
 */
public class ProductAndConsumer1 {
    private static final ThreadPoolExecutor EXECUTOR = new ThreadPoolExecutor(3, 5, 1L,
            TimeUnit.SECONDS, new LinkedBlockingDeque<>(),
            Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Data data = new Data();
        // 创建线程1
        Future<?> submit1 = EXECUTOR.submit(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data.increase();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        // 创建线程2
        Future<?> submit2 = EXECUTOR.submit(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data.decrease();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        // 创建线程3
        Future<?> submit3 = EXECUTOR.submit(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data.increase();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        // 创建线程4
        Future<?> submit4 = EXECUTOR.submit(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data.decrease();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        Object o1 = submit1.get();
        Object o2 = submit2.get();
        Object o3 = submit3.get();
        Object o4 = submit4.get();

        EXECUTOR.shutdownNow();
    }
}

/**
 * 数字资源类
 * 等待->业务->通知
 */
class Data {
    private int number = 0;

    /**
     * +1
     */
    public synchronized void increase() throws InterruptedException {
        while (number != 0) {
            // 等待
            this.wait();
        }
        number++;
        System.out.println(Thread.currentThread().getName() + " => " + number);
        // 通知其他线程, 我+1完毕了
        this.notifyAll();
    }

    /**
     * -1
     */
    public synchronized void decrease() throws InterruptedException {
        while (number == 0) {
            // 等待
            this.wait();
        }
        number--;
        System.out.println(Thread.currentThread().getName() + " => " + number);
        // 通知其他线程, 我-1完毕了
        this.notifyAll();
    }
}